﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KC.DataAccess.Processor;

namespace KC.Presentation.ProcessAggregator.Plugins
{
	public partial class RssPluginForm : UserControl
	{
		public RssPluginForm()
		{
			InitializeComponent();
			dc = new ProcessorDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["Processor"].ConnectionString);
		}

		ProcessorDataContext dc;

		private void RssPlugin_Load(object sender, EventArgs e)
		{
			timer1.Start();
			LoadChannels();
		}

		private void LoadChannels()
		{
			lbChannels.DataSource = from c in dc.RssChannels
									orderby c.Title
									select c;
		}
		private void lbChannels_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (Environment.StackTrace.Contains("LoadChannels()") && !Environment.StackTrace.Contains("RssPlugin_Load"))
				return;

			if (lbChannels.SelectedItem == null) return;
			RssChannel chan = (RssChannel)lbChannels.SelectedItem;

			dc.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, chan);
			lbItems.DataSource =
				from ri in dc.RssItems 
				where ri.RssChannelID == chan.ID 
				orderby ri.pubDate descending, ri.Title
				select ri;
		}
		private void lbItems_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (Environment.StackTrace.Contains("LoadChannels()") && !Environment.StackTrace.Contains("RssPlugin_Load"))
				return;

			RssItem ri = (RssItem)lbItems.SelectedItem;
			if (ri == null) return;
			webBrowser1.ScriptErrorsSuppressed = true;
			txtItem.Text = 
				System.Web.HttpUtility.HtmlDecode(
				System.Text.RegularExpressions.Regex.Replace(
				ri.Description.Trim()
					.Replace("<br>","\r\n").Replace("<br />","\r\n").Replace("<p>", "\r\n")
					.Replace("<ul","\r\n<ul").Replace("<ol","\r\n<ol")
					.Replace("<li>"," - ").Replace("</li>","\r\n")

					.Trim()
				, @"<.*?>", ""));
			if (!string.IsNullOrEmpty(ri.URL))
				webBrowser1.Navigate(ri.URL);
		}

		private void btnAddChannel_Click(object sender, EventArgs e)
		{
			RequestString rs = new RequestString("Enter the RSS Feed Channel URL:");
			if (rs.ShowDialog() == DialogResult.OK)
				try {
					// Download, parse, and insert the new RSS Channel
					System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
					System.Net.WebClient wc = new System.Net.WebClient();
					string result = wc.DownloadString(rs.result);
					xDoc.LoadXml(result);
					RssChannel chan = KC.Business.Processor.Plugins.JobProcessors.RssProcessor.ParseChannel(rs.result, xDoc);
					dc.RssChannels.InsertOnSubmit(chan);
					dc.SubmitChanges();

					// Reload channels and select the new channel
					LoadChannels();
				}
				catch (Exception ex)
				{
					KC.Business.Processor.Processor.LogError(ex);
					MessageBox.Show("Failed to add new channel due to error:\r\n\r\n" + ex.Message);
				}
		}

		private void timer1_Tick(object sender, EventArgs e)
		{
			RssChannel chan = (RssChannel)lbChannels.SelectedItem;
			string targetURL = chan == null ? "" : chan.RssURL;

			RssItem item = (RssItem)lbItems.SelectedItem;
			string targetTitle = item == null ? "" : item.Title;

			LoadChannels();

			if (targetURL != "")
				foreach (RssChannel chan2 in lbChannels.Items)
					if (chan2.RssURL == targetURL.Trim())
					{
						lbChannels.SelectedItem = chan2;
						break;
					}

			if (targetTitle != "")
				foreach (RssItem item2 in lbItems.Items)
					if (item2.Title == targetTitle)
					{
						lbItems.SelectedItem = item2;
						break;
					}
		}

	}
}
